package com.dotstone.chipism.activity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;

import com.dotstone.chipism.R;
import com.dotstone.chipism.bean.Home;
import com.dotstone.chipism.bean.HttpURL;
import com.dotstone.chipism.ui.login.LoginActivity;
import com.dotstone.chipism.util.DeviceManager;
import com.dotstone.chipism.util.NetUtil;
import com.dotstone.chipism.util.SPUtils;
import com.dotstone.chipism.util.SocketManager;
import com.dotstone.chipism.util.StatusBarHeightManager;
import com.umeng.analytics.MobclickAgent;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;

public class WelcomeActivity extends AppCompatActivity {
	private Dialog dialog_download;
	private ProgressDialog pd;
	private int lastProgress;

	@Override
	protected void onCreate(@Nullable Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_welcome);
		Log.e("wmy", getClass().getSimpleName() + " " + getPackageName());
		pd = new ProgressDialog(this, ProgressDialog.THEME_HOLO_LIGHT);
		checkTimeout();
		initWindow();
		DeviceManager.getInstance().setmSDKVersion(Integer.valueOf(Build.VERSION.SDK));
		getCurrentVersion();
	}

	private void initWindow() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			// 透明状态栏
			getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			// 透明导航栏
			getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
			int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
			int resourceId1 = getResources().getIdentifier("navigation_bar_height", "dimen", "android");
			int statusBarHeight = getResources().getDimensionPixelSize(resourceId);
			int navigationBarHeight = getResources().getDimensionPixelSize(resourceId1);
			StatusBarHeightManager.getInstance().setH(statusBarHeight);
		}
		// Display display = this.getWindowManager().getDefaultDisplay();
		// int h = display.getHeight();
		// int w = display.getWidth();
		// DisplayMetrics metrics = new DisplayMetrics();
		// display.getMetrics(metrics);
		// float dpi = metrics.density;
		// int DPI = metrics.densityDpi;
		// Log.i("wmy", getClass().getSimpleName() + " h = " + h + " w = " + w);
		// Log.i("wmy", getClass().getSimpleName() + " dpi = " + dpi + " DPI = "
		// + DPI);
	}

	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
		// checkNewVersion();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		MobclickAgent.onPause(this);
	}

	private boolean isSuccess = false;
	private boolean isJump = false;

	protected void checkTimeout() {
		new Thread() {
			public void run() {
				try {
					sleep(2000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				if (isSuccess) {
					return;
				}
				jump();
			};
		}.start();

	}

	private void toast(int txt) {
		Toast.makeText(this, txt, Toast.LENGTH_SHORT).show();
	}

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			if (isJump) {
				return;
			}
			isSuccess = true;
			if (msg.what == 2) {
				String ret = (String) msg.obj;
				try {
					Log.d("test", "新版本返回值" + ret);
					JSONObject o = new JSONObject(ret);
					int remoteVersion = Integer.parseInt(o.getString("appVersion"));
					String url = o.getString("appUrl");
					Log.d("wmy", "新版本返回值" + url);
					Log.d("wmy", "新版本返回值" + url);
					Log.d("wmy", "新版本返回值" + url);
					Log.d("wmy", "新版本返回值" + url);
					int currentVersion = getCurrentVersion();
					if (currentVersion < remoteVersion) {
						SPUtils.put(WelcomeActivity.this, "upDateUrl", url);
						showUpdateConfirmDialog(url);
					} else {
						SPUtils.put(WelcomeActivity.this, "upDateUrl", "");
						jump();
					}
				} catch (Exception e) {
					e.printStackTrace();
					jump();
				}
			} else if (msg.what == 3) {
				jump();
			} else if (msg.what == 4) {
				pd.dismiss();
				toast(R.string.downloadsuccess);
				// 下载完成后安装
				String savedFilePath = (String) msg.obj;
				Intent intent = new Intent();
				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				intent.setAction(Intent.ACTION_VIEW);
				intent.setDataAndType(Uri.fromFile(new File(savedFilePath)), "application/vnd.android.package-archive");
				startActivity(intent);
				finish();
			} else if (msg.what == 5) {
				pd.dismiss();
				toast(R.string.downloadfailure);
				jump();
			} else if (msg.what == 6) {
				pd.setProgress(msg.arg1);
			}
		};
	};

	public int getCurrentVersion() {
		int versionCode = 0;
		try {
			PackageInfo pkg = getPackageManager().getPackageInfo(getPackageName(), 0);
			versionCode = pkg.versionCode;
			SocketManager.getInstance().appVersion = versionCode;
			Log.i("wmy", "获取当前version = " + SocketManager.getInstance().appVersion);
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return versionCode;
	}

	protected synchronized void jump() {
		if (isJump) {
			return;
		}
		isSuccess = true;
		isJump = true;
		// 检查token 如果token过期 跳转至登录界面
		// 如果没有过期 跳转至主界面
		checkToken();
	}

	private void checkToken() {
		String token = (String) SPUtils.get(getApplicationContext(), "token", "");
		String user_id = (String) SPUtils.get(getApplicationContext(), "user_id", "");
		SocketManager.getInstance().user_id = user_id;
		SocketManager.getInstance().token = token;
		Log.i("wmy", "当前token = " + token);
		Log.i("wmy", "当前user_id = " + user_id);
		if (token == null || token == "") {
			Intent i = new Intent();
			i.setClass(WelcomeActivity.this, LoginActivity.class);
			startActivity(i);
			finish();
		} else {

			getHouse(token);
			getShopToken();
		}
	}

	private void getShopToken() {
		RequestParams params = new RequestParams("http://api.shop.soochowlightpower.com/v2/xin.auth.signin");
		// params.addHeader("X-ECAPI-Authorization", (String)
		// SPUtils.get(getApplicationContext(), "shopToken", ""));
		String user_name = (String) SPUtils.get(getApplicationContext(), "user_name", "");
		String pwd = (String) SPUtils.get(getApplicationContext(), "password", "");
		params.setAsJsonContent(true);
		JSONObject obj = new JSONObject();
		try {
			obj.put("username", user_name);
			obj.put("password", pwd);
			Log.e("wmy", " get ShopToken = " + obj.toString());
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		params.setBodyContent(obj.toString());
		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				Log.e("wmy", "get ShopToken =" + result);
				JSONObject jsonObject;
				try {
					jsonObject = new JSONObject(result);
					JSONObject jo = jsonObject.getJSONObject("data");
					JSONObject userLogin = jo.getJSONObject("userLogin");
					String shopToken = userLogin.optString("token");
					Log.i("wmy", "shopToken = " + shopToken);
					SPUtils.put(getApplicationContext(), "shopToken", shopToken);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			@Override
			public void onCancelled(CancelledException arg0) {
				Log.e("wmy", "get all dingdan cancel");
			}

			@Override
			public void onError(Throwable arg0, boolean arg1) {
				// lt.error();
				Log.e("wmy", "get all dingdan error");
			}

			@Override
			public void onFinished() {
				Log.e("wmy", "get all dingdan finish");
			}
		});
	}

	private void getHouse(String token) {
		RequestParams params = new RequestParams(HttpURL.GET_HOME_URL);
		params.setAsJsonContent(true);
		JSONObject obj = new JSONObject();
		try {
			obj.put("key", "10000");
			obj.put("token", token);
			obj.put("requestTime", "" + System.currentTimeMillis());
			Log.d("test", "login obj = " + obj.toString());
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		params.setBodyContent(obj.toString());

		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				Log.e("Tag", "成功=" + result);
				try {
					JSONObject jsonObject = new JSONObject(result);

					int resultCode = jsonObject.optInt("resultCode");

					if (resultCode == 1) {
						JSONArray ja = jsonObject.optJSONArray("data");
						if (ja.length() < 1) {
							// Intent intent = new Intent(WelcomeActivity.this,
							// AddHouseActivity.class);
							// startActivity(intent);
							// finish();
							addDefaultHouse();
						} else {
							for (int i = 0; i < ja.length(); i++) {
								String hid = ja.getJSONObject(i).getString("hid");
								String userId = ja.getJSONObject(i).getString("userId");
								String homeName = ja.getJSONObject(i).getString("homeName");
								int status = ja.getJSONObject(i).getInt("status");
								if (status == 1) {
									DeviceManager.getInstance().homeName = homeName;
									DeviceManager.getInstance().hid = hid;
								}
								Home home = new Home(hid, userId, homeName, status);
								DeviceManager.getInstance().addHome(home);
							}
							if (DeviceManager.getInstance().hid.length() != 0) {
								Log.i("wmy", "WelcomeActivity" + SPUtils.get(getApplicationContext(), "user_id", ""));
								Intent intent = new Intent(WelcomeActivity.this, MainActivity.class);
								startActivity(intent);
								finish();
							} else {
								changeStatus(DeviceManager.getInstance().getAllHome().get(0).getHid(),
										DeviceManager.getInstance().getAllHome().get(0).getHomeName(), 1);
							}
						}

					} else {
						String errorMsg = jsonObject.getString("errorMsg");
						Intent intent = new Intent(WelcomeActivity.this, LoginActivity.class);
						startActivity(intent);
						finish();
						throw new Exception();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onError(Throwable ex, boolean isOnCallback) {
				Log.e("Tag", "错误" + ex.getMessage());
				// 清空所有本地数据，进入MainActivity
				SPUtils.clear(getApplicationContext());
				Intent intent = new Intent(WelcomeActivity.this, LoginActivity.class);
				startActivity(intent);
				finish();
			}

			@Override
			public void onCancelled(CancelledException cex) {

			}

			@Override
			public void onFinished() {
				Log.e("Tag", "完成");
			}
		});
	}

	protected void showUpdateConfirmDialog(final String url) {
		Builder builder = new Builder(this, AlertDialog.THEME_HOLO_LIGHT);
		dialog_download = builder.setMessage(R.string.getnewversion)
				.setNegativeButton(android.R.string.ok, new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						dialog_download.dismiss();
						downloadNewVersion(url);
					}
				}).create();
		dialog_download.setCancelable(false);
		dialog_download.show();
	}

	protected void downloadNewVersion(final String urlString) {
		pd.setMessage(getString(R.string.downloading));
		pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		pd.show();
		pd.setCancelable(false);
		pd.setProgress(0);

		new Thread() {
			@SuppressWarnings("resource")
			public void run() {
				try {
					InputStream input = null;
					HttpURLConnection urlConn = null;
					URL url = new URL(urlString);
					urlConn = (HttpURLConnection) url.openConnection();
					urlConn.setRequestProperty("Accept-Encoding", "identity");
					urlConn.setReadTimeout(10000);
					urlConn.setConnectTimeout(10000);
					input = urlConn.getInputStream();
					int total = urlConn.getContentLength();
					File file = null;
					OutputStream output = null;
					if (!new File(Environment.getExternalStorageDirectory().getPath() + "/cache").exists()) {
						new File(Environment.getExternalStorageDirectory().getPath() + "/cache").mkdirs();
					}
					String savedFilePath = Environment.getExternalStorageDirectory().getPath() + "/cache/chipism.apk";
					file = new File(savedFilePath);
					output = new FileOutputStream(file);
					byte[] buffer = new byte[1024];
					int temp = 0;
					int read = 0;
					while ((temp = input.read(buffer)) != -1) {
						output.write(buffer, 0, temp);
						read += temp;
						float progress = ((float) read) / total;
						int progress_int = (int) (progress * 100);
						if (lastProgress != progress_int) {
							lastProgress = progress_int;
							Message msg = new Message();
							msg.what = 6;// downloading
							msg.arg1 = progress_int;
							mHandler.sendMessage(msg);
						} else {
							// do not send msg
						}
					}
					output.flush();
					output.close();
					input.close();
					Message msg = new Message();
					msg.what = 4;
					msg.obj = savedFilePath;
					mHandler.sendMessage(msg);
				} catch (Exception e) {
					e.printStackTrace();
					mHandler.sendEmptyMessage(5);
				}
			};
		}.start();
	}

	private void addDefaultHouse() {
		RequestParams params = new RequestParams(HttpURL.HANDLE_HOME_URL);
		params.setAsJsonContent(true);
		JSONObject obj = new JSONObject();
		String token = (String) SPUtils.get(getApplicationContext(), "token", "");
		try {
			obj.put("key", "10000");
			obj.put("homeName", "我的家");
			obj.put("handleType", "1");
			obj.put("token", token);
			obj.put("requestTime", "" + System.currentTimeMillis());
			Log.d("test", "login obj = " + obj.toString());
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		params.setBodyContent(obj.toString());

		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				Log.e("Tag", "添加默认房间成功=" + result);
				try {
					JSONObject jsonObject = new JSONObject(result);

					int resultCode = jsonObject.optInt("resultCode");

					if (resultCode == 1) {
						// 上传成功后，获取家庭列表，如果返回的家庭列表只有一个 将其状态改为1 直接跳转至主界面
						getHouse();
					} else {
						// String errorMsg = jsonObject.getString("errorMsg");
						// ToastShow.Show(RegisterActivity.this, errorMsg);
						throw new Exception();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onError(Throwable ex, boolean isOnCallback) {
				Log.e("Tag", "错误" + ex.getMessage());
			}

			@Override
			public void onCancelled(CancelledException cex) {

			}

			@Override
			public void onFinished() {
				Log.e("Tag", "完成");
			}
		});
	}

	private void getHouse() {
		RequestParams params = new RequestParams(HttpURL.GET_HOME_URL);
		params.setAsJsonContent(true);
		JSONObject obj = new JSONObject();
		try {
			obj.put("key", "10000");
			obj.put("token", (String) SPUtils.get(getApplicationContext(), "token", ""));
			obj.put("requestTime", "" + System.currentTimeMillis());
			Log.d("test", "get house obj = " + obj.toString());
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		params.setBodyContent(obj.toString());

		x.http().post(params, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				Log.e("Tag", "获取房间列表成功=" + result);
				try {
					JSONObject jsonObject = new JSONObject(result);

					int resultCode = jsonObject.optInt("resultCode");
					if (resultCode == 1) {
						JSONArray ja = jsonObject.optJSONArray("data");
						if (ja.length() > 0) {
							String hid = ja.getJSONObject(0).getString("hid");
							String homeName = ja.getJSONObject(0).getString("homeName");
							changeStatus(hid, homeName, 1);
						} else {

						}
					} else {

						throw new Exception();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onError(Throwable ex, boolean isOnCallback) {
				Log.e("Tag", "错误" + ex.getMessage());
				// ToastShow.Show(getApplicationContext(),
				// getString(R.string.failed));
			}

			@Override
			public void onCancelled(CancelledException cex) {

			}

			@Override
			public void onFinished() {
				Log.e("Tag", "完成");
			}
		});
	}

	private void changeStatus(final String hid, final String name, int status) {
		if (NetUtil.isNetworkAvailable(this)) {
			RequestParams params = new RequestParams(HttpURL.HANDLE_HOME_URL);
			params.setAsJsonContent(true);
			JSONObject obj = new JSONObject();
			String token = (String) SPUtils.get(getApplicationContext(), "token", "");
			try {
				obj.put("hid", hid);
				obj.put("key", "10000");
				obj.put("homeName", name);
				obj.put("handleType", "2");
				obj.put("token", token);
				obj.put("status", status);
				obj.put("requestTime", "" + System.currentTimeMillis());
				Log.e("test", "更改房屋状态 = " + obj.toString());
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
			params.setBodyContent(obj.toString());

			x.http().post(params, new Callback.CommonCallback<String>() {
				@Override
				public void onSuccess(String result) {
					Log.e("Tag", "成功=" + result);
					try {
						JSONObject jsonObject = new JSONObject(result);

						int resultCode = jsonObject.optInt("resultCode");

						if (resultCode == 1) {
							DeviceManager.getInstance().hid = hid;
							DeviceManager.getInstance().homeName = name;
							Intent intent = new Intent(WelcomeActivity.this, MainActivity.class);
							startActivity(intent);
							finish();
						} else {
							throw new Exception();
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

				@Override
				public void onError(Throwable ex, boolean isOnCallback) {
					Log.e("Tag", "错误" + ex.getMessage());
				}

				@Override
				public void onCancelled(CancelledException cex) {

				}

				@Override
				public void onFinished() {
					Log.e("Tag", "完成");
				}
			});
		} else {
			// ToastShow.Show(getApplicationContext(),
			// getString(R.string.nonetwork));
		}
	}

}
